<template>
  <div class="lab-file" v-loading="loading">
    <el-form label-width="80px" label-position="right">
      <el-row :gutter="4">
        <template v-if="templates.length > 0">
          <el-col :span="6">
            <el-form-item label="选择模板">
              <el-select  v-model="entityInfo.templateId" style="width: 100%" clearable>
                <template v-for="option in templates">
                  <el-option :key="option.templateId" :value="option.templateId" :label="option.templateName"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="生成类型">
              <el-radio-group v-model="entityInfo.suffix">
                <el-radio label="docx">docx</el-radio>
                <el-radio label="pdf">pdf</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </template>
        <el-col v-if="signConfs.length > 0" :span="8">
          <el-form-item label="选择签名">
            <el-select  v-model="entityInfo.confIds" multiple style="width: 100%" clearable>
              <template v-for="option in signConfs">
                <el-option :key="option.confId" :value="option.confId" :label="option.confName"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="width: 100%" label-width="0px">
            <template v-if="templates.length > 0">
              <el-button type="primary" icon="el-icon-document" @click="createReport(true)">生成</el-button>
              <el-button type="info" icon="el-icon-view" @click="createReport(false)">预览</el-button>
            </template>
            <el-button v-if="signConfs.length > 0" type="success" icon="iconfont icon-form-sign-two" @click="signReport">签名</el-button>
            <el-button type="warning" icon="el-icon-download" @click="downReport">下载</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table ref="tableRef" :data="dataSource" row-key="resourceId" border stripe @row-click="handleRowClick"  v-loading="loading">
      <el-table-column type="index" label="序号" align="center"></el-table-column>
      <el-table-column label="文件名" align="center" prop="resourceName"></el-table-column>
      <el-table-column label="文件类型" align="center" prop="resourceSuffix"></el-table-column>
      <el-table-column label="更新日期" align="center" prop="updateAt" width="230px"></el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <div slot="header" slot-scope="scope">
          <el-upload
              v-if="getLocalValue(element.props.entityValue)"
              :action="uploadUrl"
              :headers="uploadHeader"
              :on-success="uploadSuccess"
              :data="uploadData"
              :show-file-list="false"
          >
            <el-button type="primary" icon="el-icon-upload2" title="上传"></el-button>
          </el-upload>
          <div v-else>操作</div>
        </div>
        <div slot-scope="scope">
          <el-button circle type="success" icon="el-icon-view" @click="perview(scope.row)" title="预览"></el-button>
          <el-button circle type="info" icon="el-icon-download" @click="download(scope.row)" title="下载"></el-button>
          <el-button circle type="danger" icon="el-icon-delete-solid" @click="removeData(scope.row)" title="删除"></el-button>
          <el-button v-if="scope.row.parentId" circle type="warning" icon="el-icon-refresh-left" @click="cancelSign(scope.row)" title="撤销签名"></el-button>
        </div>
      </el-table-column>
    </el-table>
    <div class="lab-table-page">
      <div style="display: inline-flex">
        <el-pagination
            :disabled="loading"
            :current-page="pageInfo.page"
            :page-sizes="[5, 10, 15, 20, 50, 100]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <el-button-group style="padding: 2px 5px">
          <el-button icon="el-icon-refresh" title="刷新" :disabled="loading" @click="loadSource([])" />
        </el-button-group>
      </div>
    </div>
  </div>
</template>

<script>
import LabEvent from "../../mixins/LabEvent";
import LabBase from "../../mixins/LabBase";
import Util from "../../utils/Util";
import ideaTable from "../../mixins/IdeaTable";

export default {
  name: "LabReport",
  mixins: [LabBase,LabEvent,ideaTable],
  data(){
    return {
      templates: [],
      signConfs: [],
      entityInfo: { suffix: 'pdf', confIds: [] },
    }
  },
  computed: {
    uploadUrl(){
      if (this.labDesign.switch) {
        return '#'
      } else {
        return this.appendUrl(Util.mergeUrl(process.env.VUE_APP_BASE_API,'/resource/upload'))
      }
    },
    uploadHeader(){
      return { Authorization: 'Bearer ' + this.$AuthStorage.getAccessToken() }
    },
    uploadData(){
      const data = Util.copy(this.modelData)
      data.entityValue = this.getLocalValue('entityValue')
      data.entityType = this.getLocalValue('entityType')
      return data
    },
    perviewUrl () {
      return Util.mergeUrl(process.env.VUE_APP_BASE_API, '/resource/preview/')
    },
    downLoadUrl () {
      return Util.mergeUrl(process.env.VUE_APP_BASE_API, '/resource/download/')
    }
  },
  created() {
    this.$LabRender.autoFill(this.element, this)
    const { entityType, entityValue, filterOp } = this.element.props
    this.addFilter({ field: 'entityType',op:'=',value: this.getLocalValue(entityType) })
    this.addFilter({ field: 'entityType',op:filterOp,value: this.getLocalValue(entityValue) })
    this.pageInfo.pageSize = 10
    this.queryUrl = '/resource/queryPage'
    this.removeUrl = '/resource/delete/'
    this.rowKey = 'resourceId'
    // this.dataSource.push({resourceId: '00',resourceName: '测试'})
    this.loadSource()
    this.loadTemplates()
    this.loadSignConf()
  },
  methods: {
    appendUrl(url) {
      const { callDb, callStore } = this.element.props
      let newUrl = url + '?appId=' + this.appInfo.appId
      if (callDb) {
        newUrl += '&callDb=' + callDb
      }
      if (callStore) {
        newUrl += '&callStore=' + callStore
      }
      return newUrl
    },
    getLocalValue(key){
      if (!Util.isEmpty(key)) {
        const confVal = Util.callPropValue(this.element.props,key)
        if (confVal) {
          const value = Util.callPropValue(this.modelData,confVal)
          return value || confVal
        }
      }
      return ''
    },
    loadTemplates() {
      const { templateLabel } = this.element.props
      if (!templateLabel) {
        this.templates = []
        return
      }
      this.$post('/reportTemplate/queryPage', {
        page:1, pageSize: 20, filters: [{field: 'templateLabel',op:'=',value: templateLabel}]
      }).then(res => {
        this.templates = []
        this.$resultMsg(this, res, '模板获取异常', true)
        if (res.code === 200) {
          this.templates = res.data.records || []
        }
      })
    },
    loadSignConf() {
      const { signLabel } = this.element.props
      if (!signLabel) {
        this.signConfs = []
        return
      }
      const { jobs, roles, userId, branchId, groupId } = this.userInfo
      const authBody = { userId, jobs, branchId, groupId, roles, page: 1,pageSize: 50 }
      this.$post('/signAuth/config/' + signLabel, authBody).then(res => {
        this.signConfs = []
        this.$resultMsg(this, res, '签名配置异常', true)
        if (res.code === 200) {
          this.signConfs = res.data.records || []
        }
      })
    },
    uploadSuccess (response) {
      this.$resultMsg(this, response)
      if (response.code === 200) {
        this.loadSource()
      }
    },
    perview (row) {
      if (row.storeUrl && (row.storeUrl.includes('http://') || row.storeUrl.includes('https://'))) {
        window.open(row.storeUrl)
      } else if (row.resourceId) {

        window.open(this.appendUrl(this.perviewUrl + row.resourceId) + '&access_token=' + this.$AuthStorage.getAccessToken())
      }
    },
    download (row) {
      if (row.storeUrl && (row.storeUrl.includes('http://') || row.storeUrl.includes('https://'))) {
        window.open(row.storeUrl)
      } else if (row.resourceId) {
        window.open(this.appendUrl(this.downLoadUrl + row.resourceId) + '&access_token=' + this.$AuthStorage.getAccessToken())
      }
    },
    cancelSign(row) {
      // 撤销签名
    },
    createReport(saveFlag) {
      this.$post('/appInfo/createReport', {
        templateId: this.entityInfo.templateId,
        args: this.modelData, saveFlag: saveFlag,
      }).then(res => {
        this.$resultMsg(this, res)
      })
    },
    signReport() {

    },
    downReport() {

    }
  }
}
</script>

<style scoped>

</style>
